package io.renren.modules.app.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import io.renren.common.utils.MyRandomCode;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.entity.EarningsRecordingEntity;
import io.renren.modules.app.entity.vo.QueryMyTeamParam;
import io.renren.modules.app.entity.vo.SelectMyTeanData;
import io.renren.modules.app.service.EarningsRecordingService;
import io.renren.modules.app.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.UserService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;


/**
 * 用户表
 *
 * @date 2022-04-20 22:37:44
 */
@RestController
@RequestMapping("app/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private EarningsRecordingService earningsRecordingService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("generator:user:info")
    public R info(@PathVariable("userId") Long userId) {
        UserEntity user = userService.getById(userId);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("generator:user:save")
    public R save(@RequestBody UserEntity user) {
        user.setPassword(DigestUtils.sha256Hex(user.getPassword()));
        user.setTradePass(DigestUtils.sha256Hex(user.getTradePass()));
        //随机获取8位数字邀请码
        user.setInvitationCode(MyRandomCode.generateNumbers());
        //随机获取昵称
        user.setNickname(MyRandomCode.getNickname());
        userService.save(user);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("generator:user:update")
    public R update(@RequestBody UserEntity user) {
        user.setPassword(DigestUtils.sha256Hex(user.getPassword()));
        user.setTradePass(DigestUtils.sha256Hex(user.getTradePass()));
        userService.editUser(user);

        return R.ok();
    }

    @RequestMapping("/updateStatus")
    public R updateStatus(UserEntity user) {
        userService.editUser(user);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        userService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }

    /**
     * 修改登录密码
     *
     * @param user 用户信息类
     * @return
     */
    @Login
    @PostMapping("editLoginPassword")
    public R editLoginPassword(@RequestBody UserEntity user) {
        //判断原密码是否正确
        UserEntity userEntity = new UserEntity();
        userEntity.setPassword(DigestUtils.sha256Hex(user.getPassword()));
        UserEntity users = userService.queryUserDetails(userEntity);
        if (users == null) {
            return R.error("原密码不正确，请重新输入");
        }
        if (!user.getNewPassword().equals(user.getConfirmPassword())) {
            return R.error("新密码与确认密码不一致");
        }
        user.setPassword(DigestUtils.sha256Hex(user.getNewPassword()));
        Integer integer = userService.editPassword(user);
        if (integer > 0) {
            return R.ok();
        } else {
            return R.error("修改失败");
        }
    }

    /**
     * 修改交易密码
     *
     * @param user 用户信息类
     * @return
     */
    @Login
    @PostMapping("editTradePass")
    public R editTradePass(@RequestBody UserEntity user) {
        //判断原密码是否正确
        UserEntity userEntity = new UserEntity();
        userEntity.setTradePass(DigestUtils.sha256Hex(user.getTradePass()));
        UserEntity users = userService.queryUserDetails(userEntity);
        if (users == null) {
            return R.error("原交易密码不正确，请重新输入");
        }
        if (!user.getNewPassword().equals(user.getConfirmPassword())) {
            return R.error("新密码与确认密码不一致");
        }
        user.setPassword(DigestUtils.sha256Hex(user.getTradePass()));
        Integer integer = userService.editPassword(user);
        if (integer > 0) {
            return R.ok();
        } else {
            return R.error("修改失败");
        }
    }

    /**
     * 条件查询我的团队
     *
     * @param user
     * @return
     */
    @Login
    @GetMapping("queryMyTeam")
    public R queryMyTeam(QueryMyTeamParam user) {
        if (user.getUserId() == null) {
            return R.error("用户id不能为空");
        }
        if (user.getCount() == null) {
            return R.error("筛选数据参数不能为空");
        }
        SelectMyTeanData selectMyTeanData = userService.queryMyTeam(user);
        return R.ok().put("myTeanData", selectMyTeanData);
    }


    /**
     * 统计我的团队佣金
     *
     * @param user 用户信息类
     * @return
     */
    @Login
    @GetMapping("statisticsTeamCommission")
    public R statisticsTeamCommission(UserEntity user) {
        if (StringUtils.isNull(user.getUserId())) {
            return R.error("用户id不能为空");
        }
        UserEntity userEntity = userService.queryUserDetails(user);
        //该用户邀请码
        String invitationCode = userEntity.getInvitationCode();
        UserEntity userEn = new UserEntity();
        userEn.setInviteCode(invitationCode);
        //直属下属用户
        List<UserEntity> userList = userService.queryUserList(userEn);
        List<Long> userIds = userList.stream().map(UserEntity::getUserId).distinct().collect(Collectors.toList());
        //获取收益记录
        List<EarningsRecordingEntity> earningsList = earningsRecordingService.getEarningsListByUserIdsgetEarningsRecord(userIds);
        //统计收益金额(佣金)
        BigDecimal oneCommission = earningsList.stream().map(EarningsRecordingEntity::getEarningsAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

        //一级下属邀请码集合
        List<String> invitationCode1 = new ArrayList<>();
        for (UserEntity users : userList) {
            if (StringUtils.isNotEmpty(users.getInvitationCode())) {
                invitationCode1.add(users.getInvitationCode());
            }
        }
        //二级用户
        List<UserEntity> userList2 = userService.queryUserListByInviteCodes(invitationCode1);
        List<Long> userIds2 = userList2.stream().map(UserEntity::getUserId).distinct().collect(Collectors.toList());
        //获取收益记录
        List<EarningsRecordingEntity> earningsList2 = earningsRecordingService.getEarningsListByUserIdsgetEarningsRecord(userIds2);
        //统计收益金额(佣金)
        BigDecimal twoCommission = earningsList2.stream().map(EarningsRecordingEntity::getEarningsAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

        //二级下属邀请码集合
        List<String> invitationCode2 = new ArrayList<>();
        for (UserEntity user2 : userList2) {
            if (StringUtils.isNotEmpty(user2.getInvitationCode())) {
                invitationCode2.add(user2.getInvitationCode());
            }
        }
        //三级用户
        List<UserEntity> userList3 = userService.queryUserListByInviteCodes(invitationCode2);
        List<Long> userIds3 = userList3.stream().map(UserEntity::getUserId).distinct().collect(Collectors.toList());
        //获取收益记录
        List<EarningsRecordingEntity> earningsList3 = earningsRecordingService.getEarningsListByUserIdsgetEarningsRecord(userIds3);
        //统计收益金额(佣金)
        BigDecimal threeCommission = earningsList3.stream().map(EarningsRecordingEntity::getEarningsAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

        HashMap<String, Object> map = new HashMap<>();
        map.put("oneCommission", oneCommission);
        map.put("twoCommission", twoCommission);
        map.put("threeCommission", threeCommission);
        return R.ok().put("data", map);
    }

}
